<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="Vue3.0 七大亮点是什么">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2021-06-10-what-are-the-seven-highlights-of-vue3.0/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">
  <meta property="article:published_time" content="2021-06-10T03:30:15.000Z">
  <meta property="article:modified_time" content="2021-06-10T03:30:15.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="Vue">
  <meta property="article:tag" content="Vue3.0">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2021-06-10-what-are-the-seven-highlights-of-vue3.0/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>Vue3.0 七大亮点是什么 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%A7%E8%83%BD%E6%AF%942-x%E5%BF%AB1-2%EF%BD%9E2%E5%80%8D"><span class="nav-number">1.</span> <span class="nav-text">性能比2.x快1.2～2倍</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#diff%E7%AE%97%E6%B3%95%E7%9A%84%E4%BC%98%E5%8C%96"><span class="nav-number">1.1.</span> <span class="nav-text">diff算法的优化</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#render%E9%98%B6%E6%AE%B5%E7%9A%84%E9%9D%99%E6%80%81%E6%8F%90%E5%8D%87%EF%BC%88render%E9%98%B6%E6%AE%B5%E6%8C%87%E7%94%9F%E6%88%90%E8%99%9A%E6%8B%9Fdom%E6%A0%91%E7%9A%84%E9%98%B6%E6%AE%B5%EF%BC%89"><span class="nav-number">1.2.</span> <span class="nav-text">render阶段的静态提升（render阶段指生成虚拟dom树的阶段）</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E4%BE%A6%E5%90%AC%E7%BC%93%E5%AD%98"><span class="nav-number">1.3.</span> <span class="nav-text">事件侦听缓存</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8C%89%E9%9C%80%E7%BC%96%E8%AF%91%EF%BC%8C%E4%BD%93%E7%A7%AF%E6%AF%94Vue2-x%E6%9B%B4%E5%B0%8F%EF%BC%88Tree-shaking%EF%BC%89"><span class="nav-number">2.</span> <span class="nav-text">按需编译，体积比Vue2.x更小（Tree shaking）</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#Compostion-API-%E7%BB%84%E5%90%88API-%E6%B3%A8%E5%85%A5API"><span class="nav-number">3.</span> <span class="nav-text">Compostion API: 组合API&#x2F;注入API</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9B%B4%E5%A5%BD%E7%9A%84TS%E6%94%AF%E6%8C%81"><span class="nav-number">4.</span> <span class="nav-text">更好的TS支持</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B8%B2%E6%9F%93API%EF%BC%88Custom-Renderer-API%EF%BC%89"><span class="nav-number">5.</span> <span class="nav-text">自定义渲染API（Custom Renderer API）</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9B%B4%E5%85%88%E8%BF%9B%E7%9A%84%E7%BB%84%E4%BB%B6"><span class="nav-number">6.</span> <span class="nav-text">更先进的组件</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#Fragment%E7%BB%84%E4%BB%B6"><span class="nav-number">6.1.</span> <span class="nav-text">Fragment组件</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#Suspense%E7%BB%84%E4%BB%B6"><span class="nav-number">6.2.</span> <span class="nav-text">Suspense组件</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9B%B4%E5%BF%AB%E7%9A%84%E5%BC%80%E5%8F%91%E4%BD%93%E9%AA%8C%EF%BC%88vite%E5%BC%80%E5%8F%91%E6%9E%84%E5%BB%BA%E5%B7%A5%E5%85%B7%EF%BC%89"><span class="nav-number">7.</span> <span class="nav-text">更快的开发体验（vite开发构建工具）</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93%EF%BC%9A"><span class="nav-number">8.</span> <span class="nav-text">总结：</span></a></li>
                </ol>
                </li>
                <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2021-06-10-what-are-the-seven-highlights-of-vue3.0/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              Vue3.0 七大亮点是什么
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2021-06-10 11:30:15" itemprop="dateCreated datePublished" datetime="2021-06-10T11:30:15+08:00">2021-06-10</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/Vue3-0/" itemprop="url" rel="index"><span itemprop="name">Vue3.0</span></a>
                  </span>
                </span>


                <span id="/blob/2021-06-10-what-are-the-seven-highlights-of-vue3.0/" class="post-meta-item leancloud_visitors" data-flag-title="Vue3.0 七大亮点是什么" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p><a target="_blank" rel="noopener" href="https://github.com/jwenjian/visitor-count-badge"><img src="" data-original="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/" alt="总访客数量"></a></p>
            <p>原文地址：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/p2k7rRCMlqvUr4u2xaeeaw">https://mp.weixin.qq.com/s/p2k7rRCMlqvUr4u2xaeeaw</a></p>
            <h2 id="性能比2-x快1-2～2倍"><a href="#性能比2-x快1-2～2倍" class="headerlink" title="性能比2.x快1.2～2倍"></a>性能比2.x快1.2～2倍</h2>
            <h3 id="diff算法的优化"><a href="#diff算法的优化" class="headerlink" title="diff算法的优化"></a>diff算法的优化</h3>
            <p>在vue2中，虚拟dom是全量比较的。</p>
            <p>在vue3中，增加了静态标记PatchFlag。在创建vnode的时候，会根据vnode的内容是否可以变化，为其添加静态标记PatchFlag。diff的时候，只会比较有PatchFlag的节点。PatchFlag是有类型的，比如一个可变化文本节点，会将其添加PatchFlag枚举值为TEXT的静态标记。这样在diff的时候，只需比对文本内容。需要比对的内容更少了。PatchFlag还有动态class、动态style、动态属性、动态key属性等枚举值。</p>
            <h3 id="render阶段的静态提升（render阶段指生成虚拟dom树的阶段）"><a href="#render阶段的静态提升（render阶段指生成虚拟dom树的阶段）" class="headerlink" title="render阶段的静态提升（render阶段指生成虚拟dom树的阶段）"></a>render阶段的静态提升（render阶段指生成虚拟dom树的阶段）</h3>
            <p>在vue2中，一旦检查到数据变化，就会re-render组件，所有的vnode都会重新创建一遍，形成新的vdom树。</p>
            <p>在vue3中，对于不参与更新的vnode，会做静态提升，只会被创建一次，在re-render时直接复用。</p>
            <p>静态提升可以理解为第一次render不参与更新的vnode节点的时候，保存它们的引用。re-render新vdom树时，直接拿它们的引用过来即可，无需重新创建。</p>
            <h3 id="事件侦听缓存"><a href="#事件侦听缓存" class="headerlink" title="事件侦听缓存"></a>事件侦听缓存</h3>
            <p>在vue2中，我们写的@click=”onClick”也是被当作动态属性，diff的时候也要对比。但我们知道它不会变化，比如变成@click=”onClick2”，绑定别的值。</p>
            <p>在vue3中，如果事件是不会变化的，会将onClick缓存起来（跟静态提升达到的效果类似），该节点也不会被标记上PatchFlag（也就是无需更新的节点）。这样在render和diff两个阶段，事件侦听属性都节约了不必要的性能消耗。</p>
            <p>我曾经维护过一个拥有很庞大dom树的页面。由于节点非常多，无需参与更新的节点也很多，使用vue2的情况下，在render和diff两个阶段，消费了很多性能，如果当时有vue3的话，我想性能会被优化很多。</p>
            <h2 id="按需编译，体积比Vue2-x更小（Tree-shaking）"><a href="#按需编译，体积比Vue2-x更小（Tree-shaking）" class="headerlink" title="按需编译，体积比Vue2.x更小（Tree shaking）"></a>按需编译，体积比Vue2.x更小（Tree shaking）</h2>
            <p>在vue3中，可以如下面这样引用vue的功能函数，如果你的项目没有用到watch，那编译时就会把tree shaking掉。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">import &#123; computed, watch, nextTick &#125; from &quot;vue&quot;;</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>利用的就是 ES6 模块系统import/export。</p>
            <h2 id="Compostion-API-组合API-注入API"><a href="#Compostion-API-组合API-注入API" class="headerlink" title="Compostion API: 组合API/注入API"></a>Compostion API: 组合API/注入API</h2>
            <p>这里要说到代码的组织方式，传统的网页是html/css/javascript（结构/样式/逻辑）分离。vue/react通过组件化的方式，将联系紧密的结构/样式/逻辑放在一起，有利于代码的维护。</p>
            <p>compostion api更进一步，着力于JavaScript（逻辑）部分，将逻辑相关的代码放在一起，近而有利于代码的维护。</p>
            <p>在vue2的组件内，使用的是Option API风格(data/methods/mounted)来组织的代码，这样会让逻辑分散，举个例子就是我们完成一个计数器功能，要在data里声明变量，在methods定义响应函数，在mounted里初始化变量，如果在一个功能比较多、代码量比较大的组件里，你要维护这样一个功能，就需要在data/methods/mounted反复的切换到对应位置，然后进行代码的更改。</p>
            <p>在vue3中，使用setup函数。如下所示跟count相关的逻辑，都放到counter.js文件里，跟todo相关的逻辑放到todos.js里。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">import useCounter from &#39;.&#x2F;counter&#39;</span><br><span class="line">import useTodo from &#39;.&#x2F;todos&#39;</span><br><span class="line"></span><br><span class="line">setup()&#123;</span><br><span class="line">  let &#123; val, todos, addTodo &#125; &#x3D; useTodo()</span><br><span class="line">  let &#123;count,add&#125; &#x3D; useCounter() </span><br><span class="line">  return &#123;</span><br><span class="line">    val, todos, addTodo,</span><br><span class="line">    count,add,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>在我看来这就是Compostion API最大的特点，以功能为单位的代码组织方式。同时它可以让代码更易重用。</p>
            <p>说到重用，Compostion API的方式也比mixin的方式好很多，你可以清楚的看到组件使用的数据和方法来自哪个模块，而mixin进组件的功能，常常会让我们困惑此功能来自哪个mixin。</p>
            <h2 id="更好的TS支持"><a href="#更好的TS支持" class="headerlink" title="更好的TS支持"></a>更好的TS支持</h2>
            <p>vue2不适合使用ts，原因在于vue2的Option API风格。options是个简单对象，而ts是一种类型系统、面向对象的语法。两者有点不匹配。</p>
            <p>在vue2结合ts的具体实践中，要用 vue-class-component 强化 vue 组件，让 Script 支持 TypeScript 装饰器，用 vue-property-decorator 来增加更多结合 Vue 特性的装饰器，最终搞的ts的组件写法和js的组件写法差别挺大。</p>
            <p>在vue3中，量身打造了defineComponent函数，使组件在ts下，更好的利用参数类型推断 。Composition API 代码风格中，比较有代表性的api就是 ref 和 reactive，也很好的支持了类型声明。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">import &#123; defineComponent, ref &#125; from &#39;vue&#39;</span><br><span class="line"> </span><br><span class="line">const Component &#x3D; defineComponent(&#123;</span><br><span class="line">    props: &#123;</span><br><span class="line">        success: &#123; type: String &#125;,</span><br><span class="line">        student: &#123;</span><br><span class="line">          type: Object as PropType&lt;Student&gt;,</span><br><span class="line">          required: true</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    setup() &#123;</span><br><span class="line">      const year &#x3D; ref(2020)</span><br><span class="line">      const month &#x3D; ref&lt;string | number&gt;(&#39;9&#39;)</span><br><span class="line">     </span><br><span class="line">      month.value &#x3D; 9 &#x2F;&#x2F; OK</span><br><span class="line">     const result &#x3D; year.value.split(&#39;&#39;) &#x2F;&#x2F; &#x3D;&gt; Property &#39;split&#39; does not exist on type &#39;number&#39;</span><br><span class="line"> &#125;</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="自定义渲染API（Custom-Renderer-API）"><a href="#自定义渲染API（Custom-Renderer-API）" class="headerlink" title="自定义渲染API（Custom Renderer API）"></a>自定义渲染API（Custom Renderer API）</h2>
            <p>下面我们可以看到vue2和vue3的入口写法有所不同</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&#x2F;&#x2F; vue2</span><br><span class="line">import Vue from &#39;vue&#39;</span><br><span class="line">import App from &#39;.&#x2F;App.vue&#39;</span><br><span class="line">new Vue(&#123; &#x3D;&gt; h(App)&#125;).$mount(&#39;#app&#39;)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; vue3</span><br><span class="line">const &#123; createApp &#125;  from &#39;vue&#39;</span><br><span class="line">import App from &quot;.&#x2F;src&#x2F;App&quot;</span><br><span class="line">createApp(App).mount((&#39;#app&#39;)</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>vue官方实现的 createApp 会给我们的 template 映射生成 html 代码，但是要是你不想渲染生成到 html ，而是要渲染生成到 canvas 之类的不是html的代码的时候，那就需要用到 Custom Renderer API 来定义自己的 render 渲染生成函数了。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&#x2F;&#x2F; 你自己实现一个createApp，比如是渲染到canvas的。</span><br><span class="line">import &#123; createApp &#125; from &quot;.&#x2F;runtime-render&quot;;</span><br><span class="line">import App from &quot;.&#x2F;src&#x2F;App&quot;; &#x2F;&#x2F; 根组件</span><br><span class="line"></span><br><span class="line">createApp(App).mount(&#39;#app&#39;);</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="更先进的组件"><a href="#更先进的组件" class="headerlink" title="更先进的组件"></a>更先进的组件</h2>
            <h3 id="Fragment组件"><a href="#Fragment组件" class="headerlink" title="Fragment组件"></a>Fragment组件</h3>
            <p>// vue2是不允许这样写的，组件必须有一个跟节点，现在可以这样写，vue将为我们创建一个虚拟的Fragment节点。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div&gt;Hello&lt;&#x2F;div&gt;</span><br><span class="line">  &lt;div&gt;World&lt;&#x2F;div&gt;</span><br><span class="line">&lt;&#x2F;template&gt;</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这样写有何好处呢？一是如果根节点不是必要的，无需创建了，减少了节点数。二是Fragment节点是虚拟的，不会DOM树中呈现。</p>
            <h3 id="Suspense组件"><a href="#Suspense组件" class="headerlink" title="Suspense组件"></a>Suspense组件</h3>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;Suspense&gt;</span><br><span class="line">  &lt;template &gt;</span><br><span class="line">    &lt;Suspended-component &#x2F;&gt;</span><br><span class="line">  &lt;&#x2F;template&gt;</span><br><span class="line">  &lt;template #fallback&gt;</span><br><span class="line">    Loading...</span><br><span class="line">  &lt;&#x2F;template&gt;</span><br><span class="line">&lt;&#x2F;Suspense&gt;</span><br><span class="line">复制代码</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>在Suspended-component完全渲染之前，备用内容会被显示出来。如果是异步组件，Suspense可以等待组件被下载，或者在设置函数中执行一些异步操作。</p>
            <h2 id="更快的开发体验（vite开发构建工具）"><a href="#更快的开发体验（vite开发构建工具）" class="headerlink" title="更快的开发体验（vite开发构建工具）"></a>更快的开发体验（vite开发构建工具）</h2>
            <p>在使用webpack作为开发构建工具时，npm run dev都要等一会，项目越大等的时间越长。热重载页有几秒的延迟，但是如果用vite来做vue3的开发构建工具，npm run dev 秒开，热重载也很快。这种开发体验真是很爽，拒绝等待。</p>
            <p>vite的原理还是用了浏览器支持import关键字了，启动项目不用webpack构建工具先构建了，浏览器直接请求路由对应的代码文件，代理服务器针对单个文件进行编译并返回。如果请求的文件里还import了其他文件，同理浏览器继续发请求，代理服务器返回。就这样实现了npm run dev时无需编译，实时请求实时编译。</p>
            <h2 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h2>
            <p>其他的，数据监听方式变成了Proxy，消除了Object.defineProperty现有的限制（例如无法检测新的属性添加），并提供更好的性能。</p>
            <p>vue3解决了vue2的一些问题，大型应用的性能问题、ts支持不友好问题，自定义渲染API解决体系架构存在的问题，如果在vue3的基础上实现weex框架会好很多。也做出了很多优化，Compostion API让代码的组织形式更好。vite开发构建工具让开发体验更好，Tree shaking让包更小、性能更优。</p>
            <p>总的来说vue3还是非常棒的，带来了很多非常好的新特性。</p>
            <h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1>
            <p><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/p2k7rRCMlqvUr4u2xaeeaw">https://mp.weixin.qq.com/s/p2k7rRCMlqvUr4u2xaeeaw</a></p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"># Vue</a>
              <a href="/tags/Vue3-0/" rel="tag"># Vue3.0</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2021-06-09-review-of-the-development-of-front-end-technology-in-2020/" rel="prev" title="2020 前端技术发展回顾">
                  <i class="fa fa-chevron-left"></i> 2020 前端技术发展回顾
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2021-06-11-using-promise-to-realize-concurrency-control/" rel="next" title="使用promise实现并发控制">
                  使用promise实现并发控制 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>